package com.zzh.myapplication.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * @Name: MarqueeTextView
 * @Description: ${todo}
 * @time 14:08
 */
public class MarqueeTextView extends TextView {

    private float _textLength = 0f;//文本长度
    private float _viewWidth = 0f;//view宽度
    private float _x = 0f;//文字的横坐标
    private float _y = 0f;//文字的纵坐标
    private float _step = 3.0f;//移动速度,默认0.5
    private Paint _paint = null;//绘图样式
    private String _text = "";//文本内容

    //播放完成回调
    private boolean _end_flag = false;
    //监听回调
    private CompleteListener _listner;

    public interface CompleteListener {
        void compelete();
    }

    public void set_listner(CompleteListener listner) {
        this._listner = listner;
    }


    public MarqueeTextView(Context context) {
        super(context);
        init();
    }

    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        //样式
        _paint = getPaint();
        _viewWidth = getMeasuredWidth();
    }

    public void set_text(String new_text) {
        _text = new_text;
        if (_text != null)
            _textLength = _paint.measureText(_text);
        //重置区域
        _x = _viewWidth;
        _y = getTextSize() + getPaddingTop();
        _end_flag = true;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        init();
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(_text, _x, _y, _paint);
        //跑到view的最左边_textLength处才算跑马灯结束
        if (_x > 0f - _textLength) {
            _x -= _step;
        } else {
            if (_end_flag) {
                _end_flag = false;
                //通知回调一次
                if (_listner != null) {
                    _listner.compelete();
                }
            }
        }
        invalidate();
    }
}
